package com.example.test.rabbit;

import cn.hutool.core.util.RandomUtil;
import com.example.test.util.JacksonUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CommonServiceImpl implements CommonService {

    private volatile long lastOpenTime;

    @Resource
    private RabbitProducer rabbitProducer;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public Long getNextId(String seqName) {
//        return commonMapper.getNextId(seqName);

        // mock
        return RandomUtil.randomLong(100L);
    }

    /**
     * 开门
     **/
    @Override
    @SneakyThrows
    public void openDoor() {
//        // 2s计时器
//        if (lastOpenTime != 0 && lastOpenTime + 2000 > System.currentTimeMillis())
//            return;
//        lastOpenTime = System.currentTimeMillis();
//        // sn
//        long controller_sn = 225045769;
//        // ip
//        String controller_ip = "192.168.87.244";
//        // data
//        int doorNo = 1; // 门号码
//
//        // 开启连接
//        WgUDPUtil.open(controller_ip);
//
//        if (WgUDPUtil.openDoor(controller_sn,doorNo))
//            log.info("远程开门成功");
//        else
//            log.info("远程开门失败");
//        // 关闭连接
//        WgUDPUtil.close();
    }

    @Override
    public void sendMsgToAISchool(int bizType, Object obj) {
        RabbitMessage rabbitMessage = new RabbitMessage();
        rabbitMessage.setBizType(bizType);
        rabbitMessage.setData(JacksonUtil.toJson(obj));

        Long messageId = getNextId("message_id");
        String msgId = String.valueOf(messageId);
        String payload = JacksonUtil.toJson(rabbitMessage);
        rabbitProducer.produce("direct.exchange.aiSchool", "aiSchool", payload, msgId);
        redisTemplate.opsForHash().put("rabbit.redis.cache", msgId, payload);
        redisTemplate.expire("rabbit.redis.cache", 3, TimeUnit.HOURS); // 三小时没有新缓存即过期
    }


}
